package com.coder520.attend.service;

import com.coder520.attend.dao.AttendMapper;
import com.coder520.attend.entity.Attend;
import com.coder520.attend.vo.QueryCondition;
import com.coder520.common.page.PageQueryBean;
import com.coder520.common.utils.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017-7-9.
 */
@Service("attendServiceImp")
public class AttendServiceImp implements AttendService {

    /**
     * 中午12点
     */
    private static final int NOON_HOUR = 12;
    private static final int NOON_MINUTE = 0;

    /**
     * 默认缺勤时长480分钟
     * 考勤正常为1，不正常为2
     */
    private static final Integer DEFAULT_ABSENCE_MINUTE = 480;
    private static final Byte DEFAULT_STATUS_NORMAL = 1;
    private static final Byte DEFAULT_STATUS_UNNORMAL = 2;
    private static final Byte WEEK_SAT = 6;
    private static final Byte WEEK_SUN = 7;

    @Autowired
    private AttendMapper attendMapper;

    private Log log = LogFactory.getLog(AttendServiceImp.class);
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    /**
      *@Author Jay
      *@Date 2017-7-9 22:10
      *@Description  签到
      */
    @Transactional
    @Override
    public void signAttend(Attend attend) throws Exception {

        try {
            Date today = new Date();
            attend.setAttendDate(today);
            Date noon = DateUtils.getDate(NOON_HOUR,NOON_MINUTE);

            attend.setAttendWeek((byte) DateUtils.getTodayWeek());
            //查询当天 此人有没有打卡记录
            Attend todayRecord = attendMapper.selectTodaySignRecord(attend.getUserId());
            if(todayRecord == null) {
                //说明打卡记录不存在
                if(today.compareTo(noon) <= 0) {
                    //表明早于或等于12点打卡   上午打卡
                    attend.setAttendDate(today);
                }else {
                    attend.setAttendEvening(today);
                }
                attendMapper.insertSelective(attend);

            }
            else {
                if(today.compareTo(noon) <= 0) {
                    //表明早于或等于12点打卡   上午打卡
                    attend.setAttendDate(today);
                    return;
                }else {
                    todayRecord.setAttendEvening(today);
                    attendMapper.updateByPrimaryKeySelective(todayRecord);

//测试回滚情况
//                    Attend attend1 = new Attend();
//                    attend1.setId(9l);
//                    attend1.setUserId(7l);
//                    attend1.setAttendDate(today);
//                    attend1.setAttendWeek((byte) 7);
//                    attendMapper.insertSelective(attend1);
                }
            }

            //中午12点前打卡都算早上打卡 如果9：30以后打卡算异常迟到
            // 以后算下午,
            // 下午打卡检查与上午时间差,不足8小时算异常,并且缺席多长时间存入  18：00这前打卡也算异常
        } catch (Exception e) {
            log.error("用户签到异常",e);
            throw e;
        }
    }

    @Override
    public PageQueryBean listAttend(QueryCondition condition) {
        //根据条件查询count 记录数目  ----有记录才查询分布数据
        int count = attendMapper.countBYCondition(condition);
        PageQueryBean pageResult = new PageQueryBean();
        if(count > 0) {

            pageResult.setPageSize(condition.getPageSize());
            pageResult.setTotalRows(count);
            pageResult.setCurrentPage(condition.getCurrentPage());

            List<Attend> attendList = attendMapper.selectAttendPage(condition);
            pageResult.setItems(attendList);
        }
        return pageResult;
    }

    @Transactional
    @Override
    public void checkAttend() {
        //获取今天周几，周末和工作日处理不一样+  quartz
        //首先获取 今天没打卡的人  给他插入打卡记录  并且设置为异常 缺勤480分钟
        List<Long> userIdList = attendMapper.selectTodayAbsence();
        if(!userIdList.isEmpty()) {
            List<Attend> attendList = new ArrayList<Attend>();
            for (long uId:userIdList) {
                Attend attend = new Attend();
                attend.setUserId(uId);
                attend.setAttendDate(new Date());
                attend.setAttendWeek((byte)DateUtils.getTodayWeek());
                if (DateUtils.getTodayWeek() == WEEK_SUN || DateUtils.getTodayWeek() == WEEK_SAT) {
                    attend.setAttendStatus(DEFAULT_STATUS_NORMAL);
                }
                else {
                    attend.setAttendStatus(DEFAULT_STATUS_UNNORMAL);
                    attend.setAbsence(DEFAULT_ABSENCE_MINUTE);
                }
                //attendMapper.insertSelective(attend);不能一个一个插
                attendList.add(attend);
            }
            //用批量插入，不要一个一个插入
            attendMapper.batchInsert(attendList);
        }
        //如果有打卡记录  检查早晚打卡 看看考勤是不是正常
        else {
            List<Attend> attendList = attendMapper.selectTodayAttendRecord();
            for (Attend attend : attendList) {
                if (attend.getAttendMorning() != null && attend.getAttendEvening() != null) {
                    int absenceTime = DateUtils.getMunite(attend.getAttendMorning(), attend.getAttendEvening());
                    attend.setAbsence(absenceTime >= DEFAULT_ABSENCE_MINUTE ? null : (DEFAULT_ABSENCE_MINUTE - absenceTime));
                    if (attend.getAbsence() != null) attend.setAttendStatus(DEFAULT_STATUS_UNNORMAL);
                } else {
                    attend.setAttendStatus(DEFAULT_STATUS_UNNORMAL);
                }
                //更新的批量更新不好弄
                attendMapper.updateByPrimaryKeySelective(attend);
            }
        }

    }
}
